package rmmk.algorithms.features.fatures;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import rmmk.algorithms.features.FrequentNumbersGlobal;
import rmmk.algorithms.features.abstraction.AbstractFeatureExtractor;
import rmmk.framework.datasources.Document;

public class NumbersWordsExtractor extends AbstractFeatureExtractor {

	Logger logger = LoggerFactory.getLogger(NumbersWordsExtractor.class);
	
	@Override
	public Double[] doCalculate(Document document) {
		HashMap<String, String> wordBase = getWordList();
		
		Double[] ret = new Double[wordBase.size()];
		
		List<Entry<String, String>> set = new ArrayList<>();
		
		for(Entry<String, String> e : wordBase.entrySet())
			set.add(e);
		
		for(int i = 0; i < ret.length; ++i)
		{
			ret[i] = (double) countApperances(document, set.get(i));
		}
		
		return ret;
	}
	
	
	private Integer countApperances(Document document,
			Entry<String, String> entry) {
		Pattern word = Pattern.compile(entry.getValue());
		Matcher wordMatch = word.matcher(document.getTEXT());
		return wordMatch.groupCount();
	}

	static HashMap<String, String> cache = null;

	private HashMap<String, String> getWordList() {
		if (cache == null) {
			HashMap<String, String> ret = new HashMap<String, String>();
			HashMap<String, HashMap<String, Integer>> all = FrequentNumbersGlobal
					.getMap();

			//String word = null;
			//Integer count = 0;

			for (Entry<String, HashMap<String, Integer>> w : all
					.entrySet()) {
				ret.put(w.getKey().toString(), this.getMostCommonWord(w.getValue()));
				logger.info("Para klasa-słowo: " + w.getKey() + " " + ret.get(w.getKey()));
			}

			cache = ret;
			return ret;
		} else
			return cache;
	}

	private String getMostCommonWord(HashMap<String, Integer> list) {
		String word = null;
		Integer count = 0;

		for (Entry<String, Integer> w : list.entrySet()) {
			if (w.getValue() >=  count) {
				word = w.getKey();
				count = w.getValue();
			}
		}

		return word;
	}

	@Override
	public int getFeatureSize() {
		return FrequentNumbersGlobal.getMap().size();
	}

}
